package com.maychat.controller;

import com.maychat.exception.BusinessException;
import com.maychat.exception.CaptchaException;
import com.maychat.exception.NoAuthException;
import com.maychat.pojo.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.io.IOException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result ex(Exception e) {
        if (e instanceof NoHandlerFoundException) {
            return Result.error("NOT FOUND", e.getMessage());
        } else if (e instanceof BusinessException be) {
            return Result.error(be.getMsg(), be.getMessage());
        } else if (e instanceof NoAuthException nae) {
            /*
                401 登录失效
             */
            return new Result(401, nae.getMsg(), nae.getMessage());
        } else if (e instanceof HandlerMethodValidationException pe) {
            /*
             2 参数格式有误
             */
            return new Result(2, "参数格式验证未通过", pe.getMessage());
        } else if (e instanceof IOException ie) {
            /*
             3 文件传输失败，可能未找到文件
             */
            return new Result(3, "文件传输失败", ie.getMessage());
        } else if (e instanceof CaptchaException ce) {
            /*
             4 验证码错误
             */
            return new Result(4, "验证码错误", ce.getMessage());
        }
        e.printStackTrace();
        return Result.error("Unknown fatal in server! Please contact administrator", e.getMessage());
    }
}
